/**
 * Created with  SublimeText 
 * @Author:      Lyle
 * @DateTime:    2016-11-01 13:28:35
 * @Description: 
 */

(function($) {

    //Listen img load
    var imgReady = (function() {
        var list = [],
            intervalId = null,

            tick = function() {
                var i = 0;
                for (; i < list.length; i++) {
                    list[i].end ? list.splice(i--, 1) : list[i]();
                };
                !list.length && stop();
            },

            stop = function() {
                clearInterval(intervalId);
                intervalId = null;
            };

        return function(url, obj, ready, load, error) {
            var onready, width, height, newWidth, newHeight,
                img = new Image();
            img.src = url;

            if (img.complete) {
                ready.call(img);
                load && load.call(img, obj);
                return;
            };

            width = img.width;
            height = img.height;

            img.onerror = function() {
                error && error.call(img);
                onready.end = true;
                img = img.onload = img.onerror = null;
            };

            onready = function() {
                newWidth = img.width;
                newHeight = img.height;
                if (newWidth !== width || newHeight !== height || newWidth * newHeight > 1024) {
                    ready.call(img);
                    onready.end = true;
                };
            };

            onready();
            img.onload = function() {
                !onready.end && onready();
                load && load.call(img, obj);
                img = img.onload = img.onerror = null;
            };

            if (!onready.end) {
                list.push(onready);
                if (intervalId === null) intervalId = setInterval(tick, 40);
            };
        };
    })();

    $.fn.imglazyload = function(opt) {

        var opt = opt || {},
            imgClass = 'imglazyload',
            tthis = this;

        var defaults = {
            sW: null,
            sH: null,
            transform: false,
            startY: 0,
            endY: $(window).height()
        };

        for (var i in defaults) {
            if (typeof(opt[i]) == 'undefined') {
                opt[i] = defaults[i];
            }
        }

        //console.log($(tthis), $(tthis).find('.' + imgClass).length);

        $(tthis).find('.' + imgClass).each(function() {
            (function(that, opt) {
                //var topPX = $(that).offset().top;
                //if (topPX >= opt.startY && topPX < opt.endY) {
                var url = $(that).attr('url');
                if (!url) { console.log('url is undefined') };
                imgReady(url, that, function(that) {}, function() {
                    var pW = $(that).parent().width(),
                        pH = $(that).parent().height(),
                        imgW = this.width,
                        imgH = this.height;
                    opt.sW = pW > 0 ? pW : opt.sW;
                    opt.sH = pH > 0 ? pH : opt.sH;
                    if (imgW / opt.sW > imgH / opt.sH) {
                        if (opt.transform) {
                            var px = -((imgW * opt.sH / imgH) - opt.sW) / 2;
                            $(that).attr({
                                'src': $(that).attr('url'),
                                'style': "height:" + opt.sH + "px;-moz-transform:translate(" + px + "px);-webkit-transform:translate(" + px + "px);transform:translate(" + px + "px)"
                            }).removeClass(imgClass);
                        } else {
                            $(that).attr({
                                'src': $(that).attr('url'),
                                'style': 'max-height:' + opt.sH + 'px'
                            }).removeClass(imgClass);
                        }
                    } else {
                        if (opt.transform) {
                            var px = -((imgH * opt.sW / imgW) - opt.sH) / 2;
                            $(that).attr({
                                'src': $(that).attr('url'),
                                'style': "width:" + opt.sW + "px;-moz-transform:translateY(" + px + "px);-webkit-transform:translateY(" + px + "px);transform:translate(" + px + "px)"
                            }).removeClass(imgClass);

                        } else {
                            $(that).attr({
                                'src': $(that).attr('url'),
                                'style': 'max-width:' + opt.sW + 'px'
                            }).removeClass(imgClass);
                        }
                    }
                });
                //}
            })(this, opt);
        });
    }

})($);
